﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetAppBlocks.Base;
using DevExpress.XtraGrid.Views.Grid;
using ProgNetComponents.Data;
using DevExpress.XtraGrid.Views.Base;
using ProgNetDxComponents.ExtenderProviders.Language;
using ProgNetComponents;

namespace ProgNetAppBlocks.Forms
{
    public partial class ProgNetSpreadSheetForm : ProgNetBaseDbForm
    {
        public ProgNetSpreadSheetForm()
        {
            InitializeComponent();
            AutoLoadLayout = true;
        }
        
        protected virtual ProgNetRecordForm GetRecordForm(object record)
        {
            return null;
        }
        protected virtual bool AllowOpen
        {
            get { return false; }
        }
        protected override void ClearValidation()
        {
            base.ClearValidation();
            foreach (DataTable dt in DataSource.Tables)
                dt.ClearErrors();
        }
        protected override bool OpenRecord()
        {
            ProgNetRecordForm f = GetRecordForm(CurrentRecordId);
            f.SpreadSheetForm = this;
            f.FormClosed += new FormClosedEventHandler(f_FormClosed);
            f.MdiParent = this.MdiParent;
            f.Show();
            this.Hide();
            return true;
        }
        [Category(Categories.ProgNetSettings)]
        public bool SaveLayoutOnExit
        {
            get;
            set;
        }
        [Category(Categories.ProgNetSettings)]
        public bool AutoLoadLayout
        {
            get;
            set;
        }

        void f_FormClosed(object sender, FormClosedEventArgs e)
        {
            if ((sender as ProgNetRecordForm).WasModified)
                this.DoOpenEntry();
            this.Show();
        }
        protected virtual bool AllowDeleteRow(DataRow r)
        {
            return true;
        }

        protected override bool Delete()
        {
            DataRow[] rows = gvMain.GetSelectadDataRows();
            if (rows != null)
            {
                foreach (DataRow r in rows)
                {
                    if (AllowDeleteRow(r))
                        r.Delete();
                }
            }
            return true;
        }

        protected virtual ObjectKeyValuePair[] GetOpenParameters()
        {
            return null;
        }

        protected override bool OpenEntry()
        {
            if (Manager.FillDataSet(DataSource, GetOpenParameters()))
                return true;
            if (!Manager.GetAutoLogExceptions)
                Manager.LastException.Log();
            return false;
        }

        protected override bool IsSingleQuery
        {
            get { return false; }
        }

        protected override void PreInitForm()
        {
            base.PreInitForm();
            if (!AllowOpen)
                bbiOtworz.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
        }

        protected Dictionary<GridView, string[]> RequiredColumns = null;
        
        protected override void ValidateAll()
        {
            base.ValidateAll();
            DataRow[] rowsToValidate = GetRowsToValidate(DataSource.Tables[SelectData.MultiRecordQueries[0].TableDataSetName]);
            if (RequiredColumns == null)
            {
                RequiredColumns = new Dictionary<GridView, string[]>();
                GridView gv = null;
                foreach (BaseView v in gcMain.ViewCollection)
                {
                    if (v is GridView)
                    {
                        gv = v as GridView;
                        if (gv.SourceView == null)
                        {
                           // gv = gv.SourceView as GridView;
                            RequiredColumns.Add(gv, modeProvider1.GetRequiredColumns(gv));
                        }
                    }
                }
            }

            foreach (DataRow r in rowsToValidate)
            {
                ValidateRow(r, gvMain);
            }
        }

        protected virtual BaseView GetViewForRow(DataRow r)
        {
            DataTable d= null;
            foreach (BaseView v in gcMain.ViewCollection)
            {
                d = v.GetSourceTableForView();
                if (d == r.Table)
                {
                    if (v.SourceView != null)
                        return v.SourceView as GridView;
                    return v;
                }
            }
            return null;
        }
        protected virtual DataRow[] GetChildRowsToValidate(DataRow r)
        {
            return r.GetAllChildRows();
        }
        protected virtual bool ValidateRow(DataRow r, GridView gv)
        {
            bool result = true;
            foreach (string s in RequiredColumns[gv])
            {
                if (r.Table.Columns.Contains(s))
                {
                    if (r[s].IsNull())
                    {
                        r.SetColumnError(s, "Ta wartość jest wymagana");
                        AddError("Kolumna " + ProgNetLanguage.sGetStringDefault(s, s).AddDoubleQuotes() + " musi byc uzupełniona");
                        result = false;
                    }
                }
            }
            DataRow[] childRows = GetChildRowsToValidate(r);
            BaseView bv = null;
            foreach (DataRow c in childRows)
            {
                bv = GetViewForRow(c);
                if (bv != null && bv is GridView)
                {
                    if (!ValidateRow(c, bv as GridView))
                    {
                        result = false;
                        gv.ExpandRow(r);
                    }
                }
            }
            return result;
        }

        protected virtual DataRow[] GetRowsToValidate(DataTable dataTable)
        {
            return dataTable.Select();
        }

        private void ModeSettings_RowDeleting(object sender, ProgNetDxComponents.ExtenderProviders.Settings.RowDeletingEventArgs e)
        {
            e.Cancel = !AllowDeleteRow(e.Row);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (this.IsAppRunning())
            {
                SetLayoutName();
                if (AutoLoadLayout)
                    layoutProvider1.LoadSavedLayout();
            }
        }
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            if (SaveLayoutOnExit)
                layoutProvider1.SaveLayout();
        }
        #region Layout
        protected virtual void SetLayoutName()
        {
            layoutProvider1.LayoutName = "S_" + SelectDataName;
            layoutProvider1.SetCurrentLayoutAsDefault();
        }

        protected virtual void bbiLayoutSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (layoutProvider1.SaveLayout())
                this.ShowDxInfoDialog("Layout zapisany");
            else
                this.ShowDxErrorDialog("Błąd zapisu Layout'u");

        }

        protected virtual void bbiLayoutRead_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!layoutProvider1.LoadSavedLayout())
                this.ShowDxErrorDialog("Błąd wczytania Layout'u");
        }

        protected virtual void bbiLayoutDefault_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if(!layoutProvider1.RestoreDefaultLayout())
                this.ShowDxErrorDialog("Błąd wczytania domyślnego Layout'u");
        }
        #endregion
    }

}
